package com.github.ghsea.framework.job.client;

import java.net.MalformedURLException;

import com.caucho.hessian.client.HessianProxyFactory;
import com.github.ghsea.framework.job.api.JobRegistry;
import com.github.ghsea.framework.job.common.AuthorityInfo;
import com.github.ghsea.framework.job.common.Endpoint;
import com.github.ghsea.framework.job.common.TriggerMetadata;
import com.github.ghsea.framework.job.common.exception.JobConfigurationException;
import com.github.ghsea.framework.job.common.exception.JobRegistryException;

public class JobRegistryClient implements JobRegistry {

	private JobServerLocator serverLocator;

	private HessianProxyFactory factory = new HessianProxyFactory();

	JobRegistryClient(JobServerLocator serverLocator) {
		this.serverLocator = serverLocator;
	}

	public void register(AuthorityInfo authority, TriggerMetadata trigger) throws JobRegistryException {

		// TODO readtimeout,collection timeout ,retry.
		Endpoint serverEndPoint = serverLocator.select();
		String serverUrl = "http://" + serverEndPoint.getIp() + ":" + serverEndPoint.getPort()
				+ serverEndPoint.getBaseAccessUrl() + "/jobRegistry";
		try {
			JobRegistry jobRegistry = (JobRegistry) factory.create(JobRegistry.class, serverUrl);
			trigger.validate();
			jobRegistry.register(authority, trigger);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JobConfigurationException jce) {
			throw new JobRegistryException(jce);
		}

	}
}
